package com.caipu.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.caipu.entity.*;
import com.caipu.mapper.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.FileCopyUtils;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class DataInitService {
    
    @Autowired
    private CategoryMapper categoryMapper;
    
    @Autowired
    private TagMapper tagMapper;
    
    @Autowired
    private DishMapper dishMapper;
    
    @Autowired
    private DishTagMapper dishTagMapper;
    
    @Autowired
    private UserMapper userMapper;
    
    @Transactional
    public void initData() throws IOException {
        // 读取data.json文件
        ClassPathResource resource = new ClassPathResource("data.json");
        byte[] bdata = FileCopyUtils.copyToByteArray(resource.getInputStream());
        String jsonStr = new String(bdata, StandardCharsets.UTF_8);
        
        JSONObject jsonData = JSON.parseObject(jsonStr);
        JSONArray dishes = jsonData.getJSONArray("dishes");
        
        // 收集所有分类和标签
        Set<String> categoryNames = new HashSet<>();
        Set<String> tagNames = new HashSet<>();
        
        for (int i = 0; i < dishes.size(); i++) {
            JSONObject dish = dishes.getJSONObject(i);
            categoryNames.add(dish.getString("category"));
            JSONArray tags = dish.getJSONArray("tags");
            for (int j = 0; j < tags.size(); j++) {
                tagNames.add(tags.getString(j));
            }
        }
        
        // 初始化分类
        Map<String, Long> categoryMap = initCategories(categoryNames);
        
        // 初始化标签
        Map<String, Long> tagMap = initTags(tagNames);
        
        // 初始化菜品
        initDishes(dishes, categoryMap, tagMap);
        
        // 初始化默认用户
        initDefaultUser();
    }
    
    private Map<String, Long> initCategories(Set<String> categoryNames) {
        Map<String, Long> categoryMap = new HashMap<>();
        
        for (String name : categoryNames) {
            // 检查是否已存在
            QueryWrapper<Category> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("name", name).eq("deleted", 0);
            Category existingCategory = categoryMapper.selectOne(queryWrapper);
            
            if (existingCategory != null) {
                categoryMap.put(name, existingCategory.getId());
            } else {
                Category category = new Category();
                category.setName(name);
                category.setDescription(name + "类菜品");
                category.setCreateTime(LocalDateTime.now());
                category.setUpdateTime(LocalDateTime.now());
                category.setDeleted(0);
                
                categoryMapper.insert(category);
                categoryMap.put(name, category.getId());
            }
        }
        
        return categoryMap;
    }
    
    private Map<String, Long> initTags(Set<String> tagNames) {
        Map<String, Long> tagMap = new HashMap<>();
        
        // 预定义标签颜色
        String[] colors = {"#f56565", "#ed8936", "#ecc94b", "#48bb78", "#38b2ac", 
                          "#4299e1", "#667eea", "#9f7aea", "#ed64a6", "#a0aec0"};
        int colorIndex = 0;
        
        for (String name : tagNames) {
            // 检查是否已存在
            QueryWrapper<Tag> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("name", name).eq("deleted", 0);
            Tag existingTag = tagMapper.selectOne(queryWrapper);
            
            if (existingTag != null) {
                tagMap.put(name, existingTag.getId());
            } else {
                Tag tag = new Tag();
                tag.setName(name);
                tag.setColor(colors[colorIndex % colors.length]);
                tag.setCreateTime(LocalDateTime.now());
                tag.setUpdateTime(LocalDateTime.now());
                tag.setDeleted(0);
                
                tagMapper.insert(tag);
                tagMap.put(name, tag.getId());
                colorIndex++;
            }
        }
        
        return tagMap;
    }
    
    private void initDishes(JSONArray dishes, Map<String, Long> categoryMap, Map<String, Long> tagMap) {
        for (int i = 0; i < dishes.size(); i++) {
            JSONObject dishJson = dishes.getJSONObject(i);
            String dishName = dishJson.getString("name");
            
            // 检查菜品是否已存在
            QueryWrapper<Dish> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("name", dishName).eq("deleted", 0);
            Dish existingDish = dishMapper.selectOne(queryWrapper);
            
            if (existingDish == null) {
                Dish dish = new Dish();
                dish.setName(dishName);
                dish.setCategoryId(categoryMap.get(dishJson.getString("category")));
                dish.setDescription("美味的" + dishName);
                // 为每个菜品生成一个默认的图片URL，使用菜品名称作为参数
                try {
                    String imageUrl = "https://via.placeholder.com/400x300/4CAF50/FFFFFF?text=" + 
                        java.net.URLEncoder.encode(dishName, "UTF-8");
                    dish.setMainImage(imageUrl);
                } catch (UnsupportedEncodingException e) {
                    dish.setMainImage("https://via.placeholder.com/400x300/4CAF50/FFFFFF?text=菜品图片");
                }
                dish.setDetailImages("[]"); // 空的详情图片数组
                dish.setCalories(dishJson.getInteger("calories"));
                dish.setCreateTime(LocalDateTime.now());
                dish.setUpdateTime(LocalDateTime.now());
                dish.setDeleted(0);
                
                dishMapper.insert(dish);
                
                // 添加标签关联
                JSONArray tags = dishJson.getJSONArray("tags");
                for (int j = 0; j < tags.size(); j++) {
                    String tagName = tags.getString(j);
                    Long tagId = tagMap.get(tagName);
                    
                    if (tagId != null) {
                        DishTag dishTag = new DishTag();
                        dishTag.setDishId(dish.getId());
                        dishTag.setTagId(tagId);
                        dishTag.setCreateTime(LocalDateTime.now());
                        
                        dishTagMapper.insert(dishTag);
                    }
                }
            }
        }
    }
    
    private void initDefaultUser() {
        // 检查是否已存在admin用户
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", "admin").eq("deleted", 0);
        User existingUser = userMapper.selectOne(queryWrapper);
        
        if (existingUser == null) {
            User user = new User();
            user.setUsername("admin");
            user.setPassword("admin123"); // 实际项目中应该加密
            user.setNickname("管理员");
            user.setCreateTime(LocalDateTime.now());
            user.setUpdateTime(LocalDateTime.now());
            user.setDeleted(0);
            
            userMapper.insert(user);
        }
    }
}